// UserService.java
package com.search_wheel.service;

import com.search_wheel.mapper.UserMapper;
import com.search_wheel.pojo.entity.User;
import com.search_wheel.pojo.vo.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 搜索用户
     */
    public SearchResult<User> searchUser(String keyword, int page, int size, String sort) {
        if (!StringUtils.hasText(keyword)) {
            return createEmptyResult(keyword, page, size, "user");
        }

        int offset = (page - 1) * size;
        List<User> users = userMapper.searchByKeyword(keyword, offset, size,sort);
        int total = userMapper.countByKeyword(keyword);

        return createSearchResult(users, total, page, size, keyword, "user");
    }

    /**
     * 获取用户详情
     */
    public User getUserDetail(Integer id) {
        if (id == null) {
            return null;
        }
        return userMapper.findById(id);
    }

    /**
     * 根据用户名查找用户
     */
    public User findByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return null;
        }
        return userMapper.findByUsername(username);
    }

    /**
     * 获取热门用户
     */
    public List<User> getPopularUsers(int limit) {
        return userMapper.findPopularUsers(limit);
    }

    private <T> SearchResult<T> createEmptyResult(String keyword, int page, int size, String type) {
        SearchResult<T> result = new SearchResult<>();
        result.setData(List.of());
        result.setTotal(0);
        result.setPage(page);
        result.setSize(size);
        result.setKeyword(keyword);
        result.setType(type);
        return result;
    }

    private <T> SearchResult<T> createSearchResult(List<T> data, int total, int page, int size, String keyword, String type) {
        SearchResult<T> result = new SearchResult<>();
        result.setData(data);
        result.setTotal(total);
        result.setPage(page);
        result.setSize(size);
        result.setKeyword(keyword);
        result.setType(type);
        return result;
    }
    // UserService.java
    public List<String> getUsernamesContaining(String keyword, int limit) {
        return userMapper.findUsernamesContaining(keyword, limit);
    }

    /**
     * 获取所有用户名（用于构建搜索词典）
     */
    public List<String> getAllUsernames() {
        return userMapper.findAllUsernames();
    }
}